package model;


import java.util.prefs.Preferences;

import static misc.Utils.GSON;

/**
 * Created with IntelliJ IDEA.
 * User: nuno-rafael-figueiredo
 * Date: 04-03-2014
 * Time: 17:38
 */
public abstract class FavoritableEntity<Key, Item extends IItem<Key>> extends KeyEntity<Key, Item> {
    public static final String FAVORITES_KEY = "favorites";

    private final KeyEntity<Key, Item> favorites = newInstance();

    @SuppressWarnings("unchecked")
    protected KeyEntity<Key, Item> newInstance() {
        return new KeyEntity<Key, Item>(arrayClass, itemClass) {
            @Override
            protected void parse() {
            }
        };
    }

    private final Preferences preferences = Preferences.userNodeForPackage(getClass());

    protected FavoritableEntity(Class<Item[]> arrayClass, Class<Item> itemClass) {
        super(arrayClass, itemClass);


        favorites.addObserver((observable, o) -> preferences.put(FAVORITES_KEY, GSON.toJson(favorites)));

        loadFavorites();
    }

    public void loadFavorites() {
        String json = preferences.get(FAVORITES_KEY, "[]");
        if (json == null || json.equals("null"))
            preferences.put(FAVORITES_KEY, json = "[]");


        System.out.println(this + "->" + json);
        Item[] array = GSON.fromJson(json, arrayClass);
        for (Item item : array)
            favorites.add(item);

        favorites.setChangedAndNotifyObservers();
    }

    public KeyEntity<Key, Item> getFavorites() {
        return favorites;
    }

    public void setFavorite(Item item) {
        favorites.add(item);
    }

    public void removeFavorite(Item item) {
        favorites.remove(item.getKey());
    }

    public boolean isFavorite(Item Item) {
        return getFavorites().containsValue(Item);
    }

    public void setFavorite(Item Item, boolean favorite) {
        if (favorite)
            setFavorite(Item);
        else
            removeFavorite(Item);
    }
}
